﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using SoftwareLogistics.SharepointClient.Models;
using SoftwareLogistics.SharepointClient.Library;
using SoftwareLogistics.SharepointClient.Library.Models;

namespace SoftwareLogistics.SharepointClient
{
    public partial class Project : PhoneApplicationPage
    {
        Services.SPListService _listService;

        public Project()
        {
            InitializeComponent();

            _listService = new Services.SPListService();
            _listService.GotListRows += (sender, args) =>
            {
                switch(args.ListMetaData.Name)
                {
                    case "Tasks": TasksList.ItemsSource = args.Rows; break;
                    case "Time": TimeList.ItemsSource = args.Rows; break;
                    case "Project": ProjectList.ItemsSource = args.Rows; break;
                }
            };

            SetDefaultFilter(ProjectPivot);
            SetDefaultFilter(TaskPivot);
            SetDefaultFilter(TimePivot); ;
        }

        private string GetFilterName(string listName)
        {
            return string.Format("{0}Filter", listName);
        }

        private void SetDefaultFilter(PivotItem item)
        {
            var listName = item.Tag.ToString();
            var filterName = GetFilterName(listName);
            SPQuery query;
            if (Common.StateBag.ContainsKey(filterName))
                query = Common.Filters[listName].First(filter => filter.Name == Common.StateBag[filterName]);
            else
                query = Common.Filters[listName].First(filter => filter.IsDefault == true);

            _listService.GetListRows(listName, query);
        }


        private void Row_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(e.AddedItems.Count == 1)
            {
                var spFormData = new SPFormData();
                spFormData.RowData = e.AddedItems[0] as SPDataRow;
                spFormData.IsEdit = true;
                spFormData.ListName = spFormData.RowData.ListName;

                var id = Common.AddToNavDictionary(spFormData);

                NavigationService.Navigate(new Uri("/DataForm.xaml?id=" + id, UriKind.Relative));
            }
        }

        private void AddTime_Click(object sender, RoutedEventArgs e)
        {
            var task = ((e.OriginalSource as Button).Tag) as SPDataRow;

            var spFormData = new SPFormData();
            spFormData.IsEdit = false;
            spFormData.ListName = "Time";
            spFormData.FormDefaults.AddValue("Task", string.Format("{0};#{1}", task.ID, task.Title));
            spFormData.FormDefaults.AddValue("User", Common.Users.CurrentUser.ID.ToString());
            spFormData.FormDefaults.AddValue("Is Billable", "TRUE");
            spFormData.FormDefaults.AddValue("Work Date", DateTime.Today.ToShortDateString());
            spFormData.FormDefaults.AddValue("Hours Worked", "0");

            var id = Common.AddToNavDictionary(spFormData);
            NavigationService.Navigate(new Uri("/DataForm.xaml?id=" + id, UriKind.Relative));
        }

        private void AddTask_Click(object sender, RoutedEventArgs e)
        {
            var project = ((e.OriginalSource as Button).Tag) as SPDataRow;

            var spFormData = new SPFormData();
            spFormData.IsEdit = false;
            spFormData.ListName = "Tasks";
            spFormData.FormDefaults.AddValue("Project", string.Format("{0};#{1}", project.ID, project.Title));

            var id = Common.AddToNavDictionary(spFormData);
            NavigationService.Navigate(new Uri("/DataForm.xaml?id=" + id, UriKind.Relative));
        }

        private void FilterButton_Click(object sender, EventArgs e)
        {
            var currentListName = (MainPivot.SelectedItem as PivotItem).Tag.ToString();

            Filter.ItemsSource = Common.Filters[currentListName];
            Filter.SelectedIndex = -1;
            FilterPanel.Visibility = System.Windows.Visibility.Visible;            
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (FilterPanel.Visibility == System.Windows.Visibility.Visible)
            {
                FilterPanel.Visibility = System.Windows.Visibility.Collapsed;
                e.Cancel = true;
            }

            base.OnBackKeyPress(e);
        }

        private void Filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 1)
            {
                FilterPanel.Visibility = System.Windows.Visibility.Collapsed;
                var query = e.AddedItems[0] as SPQuery;
                var currentListName = (MainPivot.SelectedItem as PivotItem).Tag.ToString();
                _listService.GetListRows(currentListName, query);
            }
        }
    }
}